package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartServices;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author :XingJiaCheng
 * @date :2022-2022/12/25-16:49
 * @description
 **/
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartServices cartServices;
    @PostMapping("/add")
    public R<ShoppingCart>add(@RequestBody ShoppingCart cart){
        log.info("添加购物车cart:{}", cart);
        cart.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        if (cart.getDishId()!=null){
            queryWrapper.eq(ShoppingCart::getUserId, cart.getDishId());
        }else {
            queryWrapper.eq(ShoppingCart::getSetmealId, cart.getSetmealId());
        }
        ShoppingCart cartOne = cartServices.getOne(queryWrapper);
        if (cartOne!=null){
            cartOne.setNumber(cartOne.getNumber()+1);
            cartServices.updateById(cartOne);
        }else {
            cart.setNumber(1);
            cart.setCreateTime(LocalDateTime.now());
            cartServices.save(cart);
            cartOne = cart;
        }
        return R.success(cartOne);
    }
    @GetMapping("/list")
    public R<List<ShoppingCart>>list(){
        LambdaQueryWrapper<ShoppingCart> QueryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        QueryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCarts = cartServices.list(QueryWrapper);
        return R.success(shoppingCarts);
    }
    @DeleteMapping("/clean")
    public R<String>clean(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        cartServices.remove(queryWrapper);
        return R.success("清空购物车");
    }


}
